package com.sunday.aomicaichang.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommonAdapter;
import com.sunday.common.adapter.RecylerViewHolder;
import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MallRechangeRecordFragment extends BaseFragment  {


    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private CommonAdapter<OrderItem> adapter;
    private List<OrderItem> dataSet = new ArrayList<>(6);
    private final int PRO_TYPE = 3;//采购商品
    private String orderStatuses;
    private int catId;
    private int type=1;
    public static MallRechangeRecordFragment newInstance(String orderStatuses) {
        MallRechangeRecordFragment fragment = new MallRechangeRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString("orderStatuses", orderStatuses);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_product_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            orderStatuses=getArguments().getString("orderStatuses");
        }
        initRecylerView();
        getData();
    }


    private LinearLayoutManager layoutManager;
    private int lastVisibleItem;
    private boolean isCanloadMore;
    private int pagNo = 1;
    private int pageSize = 20;

    private void initRecylerView() {
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<OrderItem>(mContext, R.layout.item_exchange_record, dataSet) {
            @Override
            public void convert(RecylerViewHolder holder, OrderItem product) {
                bind(holder, product);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pagNo = 1;
                getData();
            }
        });
    }

    private void bind(RecylerViewHolder holder, final OrderItem product) {
        if(product.getProducts()==null)return;
        ImageView imageView = holder.getView(R.id.img);
        if (!TextUtils.isEmpty(product.getProducts().get(0).getImage())) {
            Picasso.with(mContext)
                    .load(product.getProducts().get(0).getImage())
                    .error(R.mipmap.ic_product)
                    .into(imageView);
        }

        if(product.getProducts().get(0).getName()!=null){
            ((TextView) holder.getView(R.id.name)).setText(product.getProducts().get(0).getName());
        }
        if(product.getOrderNo()!=null){
            ((TextView) holder.getView(R.id.num)).setText("订单编号"+product.getOrderNo());
        }  if(product.getProducts().get(0).getCreateDate()!=null){
            ((TextView) holder.getView(R.id.time)).setText("兑换时间"+product.getProducts().get(0).getCreateDate());
        }
         holder.setOnClickListener(R.id.item, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(mContext, MallRechangeDetailActivity.class);
                intent.putExtra("orderId", product.getId());
                startActivity(intent);
            }
        });
        switch (product.getOrderStatus()){
            case ConstValue.STA_ONE:
                ((TextView) holder.getView(R.id.tv_status)).setText("待付款");
                break;
            case ConstValue.STA_TWO:
                ((TextView) holder.getView(R.id.tv_status)).setText("待配送");
                break;
            case ConstValue.STA_THREE:
                ((TextView) holder.getView(R.id.tv_status)).setText("配送中");
                break;
            case ConstValue.STA_FOUR:
                ((TextView) holder.getView(R.id.tv_status)).setText("待评价");
                break;
            case ConstValue.STA_FIVE:
                ((TextView) holder.getView(R.id.tv_status)).setText("已评价");
                break;
            case ConstValue.STA_SIX:
                ((TextView) holder.getView(R.id.tv_status)).setText("待退款");
                break;
            case ConstValue.STA_SEVEN:
                ((TextView) holder.getView(R.id.tv_status)).setText("已退款");
                break;
            case ConstValue.STA_EIGHT:
                ((TextView) holder.getView(R.id.tv_status)).setText("待退货");
                break;
            case ConstValue.STA_NINE:
                ((TextView) holder.getView(R.id.tv_status)).setText("已退货");
                break;
            case ConstValue.STA_TEN:
                ((TextView) holder.getView(R.id.tv_status)).setText("已取消");
                break;
            default:
                ((TextView) holder.getView(R.id.tv_status)).setText("已完成");
                break;
        }
    }

    private void getData() {
        String nonce= MD5Utils.random();
        String[] str1=new String[]{"type","orderStatuses","pageSize","pageNumber","nonce"};
        String[] str2=new String[]{"2",orderStatuses,String.valueOf(pageSize),String.valueOf(pagNo),nonce};
        Call<ResultDO<List<OrderItem>>> call= ApiClient.getApiAdapter().getOrderList(2,orderStatuses,pageSize,pagNo,null,null,nonce,SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO<List<OrderItem>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<OrderItem>>> call, Response<ResultDO<List<OrderItem>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                ptrFrame.refreshComplete();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (pagNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult().size() == 20) {
                        pagNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<OrderItem>>> call, Throwable t) {
                ptrFrame.refreshComplete();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
